package com.tubeonfire.model.admin;

import java.util.Collections;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.tubeonfire.entity.SiteConfig;
import com.tubeonfire.util.IdUniqueHelper;

public class SiteConfigModel {
	private static Objectify ofy;

	private static boolean isRegisted = false;

	private static ObjectifyOpts opts = null;

	private static Cache cache = null;

	private static String cachePrefix = "SiteConfig";

	public static void init() {
		if (!isRegisted) {
			isRegisted = true;
			try {
				ObjectifyService.register(SiteConfig.class);
			} catch (Exception e) {
				isRegisted = false;
			}
			try {
				cache = CacheManager.getInstance().getCacheFactory()
						.createCache(Collections.emptyMap());
			} catch (CacheException e) {
				isRegisted = false;
			}
			opts = new ObjectifyOpts().setSessionCache(true);
		}
		ofy = ObjectifyService.begin(opts);
	}

	public SiteConfigModel() {
		init();
	}

	@SuppressWarnings("unchecked")
	public static void insert(SiteConfig obj) {
		init();
		if (cache != null) {
			cache.put(cachePrefix, obj);
		}
		ofy.put(obj);
	}

	public static void delete(SiteConfig obj) {
		init();
		if (cache != null && cache.containsKey(cachePrefix)) {
			cache.remove(cachePrefix);
		}
		ofy.delete(obj);
	}

	@SuppressWarnings("unchecked")
	public static SiteConfig get() {
		init();
		try {
			boolean cached = false;
			SiteConfig obj = new SiteConfig();
			if (cache != null) {
				try {
					obj = (SiteConfig) cache.get(cachePrefix);
					if (obj != null)
						cached = true;
				} catch (Exception e) {
					cached = false;
				}
			}
			if (!cached) {
				try {
					obj = (SiteConfig) ofy.query(SiteConfig.class).get();
					if (obj == null) {
						obj = new SiteConfig();
						obj.setId(IdUniqueHelper.getId());
						insert(obj);
					}
					cache.put(cachePrefix, obj);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
			return new SiteConfig();
		}
	}
}
